package com.zhijian.warehouse.manage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.warehouse.manage.dao.UserRoleMapper;
import com.zhijian.warehouse.manage.entity.po.UserRole;
import com.zhijian.warehouse.manage.entity.vo.request.UserRoleSearchVo;
import com.zhijian.warehouse.manage.entity.vo.response.UserRoleVo;
import com.zhijian.warehouse.manage.service.UserRoleService;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 人员-角色关系表业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-01-21 14:32:50
 */
@Slf4j
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper mapper;

    @Override
    public UserRole selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public UserRoleVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByUserId(Long userId) {
        mapper.deleteByUserId(userId);
    }

    @Override
    public Long insert(UserRole userRole) {
        Date now = new Date();
        userRole.setCreateTime(now);
        userRole.setUpdateTime(now);
        return mapper.insert(userRole) > 0 ? userRole.getId() : 0L;
    }

    @Override
    public boolean update(UserRole userRole) {
        Date now = new Date();
        userRole.setUpdateTime(now);
        return mapper.updateByPrimaryKey(userRole) != 0;
    }

    @Override
    public Integer count(UserRoleSearchVo userRoleSearchVo) {
        return mapper.count(userRoleSearchVo);
    }

    @Override
    public List<UserRoleVo> selectList(UserRoleSearchVo userRoleSearchVo) {
        return mapper.selectList(userRoleSearchVo);
    }

    @Override
    public Page<UserRoleVo> selectPage(UserRoleSearchVo userRoleSearchVo) {
        //先直接查总数
        int count = count(userRoleSearchVo);
        //分页
        Page<UserRoleVo> page = new Page<>(true, count, userRoleSearchVo.getPageNum(), userRoleSearchVo.getPageSize());
        userRoleSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<UserRoleVo> responseVos = this.selectList(userRoleSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public List<Long> selectRoleIdListByUserId(Long userId) {
        return mapper.selectRolesByUserId(userId);
    }

    @Override
    public boolean insertBatch(List<UserRole> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

}